#!/usr/bin/python

## Run tests 
## Run these FS tests:
## Create 10K - 60K Files -- t/0 .. t/10000, 4K each
## Write locally
## Read locally

## Read remotly
## Search remotly

## -- now, do search tests

import sys, os
import time, random

file_chars = "qwertyuioplkjhgfdsazxcvbnm1234567890" 
#num_times = [10000, 20000, 30000, 40000, 50000, 60000]
#num_times = [100, 1000, 10000, 20000]
num_times = [ 200 ]
testing_dir = "./t"
times_write = {}
times_read = {}
num_write = 2
verbose = False
on_local = True

def do_write(testing_dir, file_size, current_run_time, text_write):
  for i in range(0, current_run_time):
    f=open(testing_dir+"/"+str(i), 'w')
    next_c = 0
    for j in range(0, file_size):
      f.write(text_write[next_c])
      next_c+=1
      if (next_c >= len(text_write)):
        next_c = 0
    f.close()
      
def do_read(testing_dir, file_size, current_run_time):
  for i in range(0, current_run_time):
    f=open(testing_dir+"/"+str(i), 'r')
    for j in range(0, file_size):
      f.readlines(file_size)
    f.close()

def do_local (testing_dir, file_size):
  global times
  
  for current_run_time in (num_times):
    text_write = random.sample(file_chars, len(file_chars))
    
    time_start_w = time.time()
    do_write(testing_dir, file_size, current_run_time, text_write)
    time_end_w = time.time()
  
    time_start_r = time.time()
    do_read (testing_dir, num_write, current_run_time)
    time_end_r = time.time()
    
    times_write[current_run_time] = (time_end_w - time_start_w)   
    times_read[current_run_time] = (time_end_r - time_start_r)   

  
def do_remote (testing_dir, num_write):
  for current_run_time in (num_times):
    time_start_r = time.time()
    do_read (testing_dir, num_write, current_run_time)
    time_end_r = time.time()
  
    times_read[current_run_time] = (time_end_r - time_start_r)   

num_write = int(sys.argv[1])

if (len(sys.argv) > 2):
  testing_dir = sys.argv[2]
  if verbose:
    print "## Running on " + testing_dir

if (len(sys.argv) > 3):
  on_local = False
  if verbose:
    print "## Running on remote host."  

#try making the testing dir
if (not os.access(testing_dir, os.F_OK)):
  os.mkdir(testing_dir) 

if on_local:
  do_local(testing_dir, pow(2,num_write))
else:
  do_remote(testing_dir, pow(2,num_write))

if verbose:
  for k in num_times:
    sys.stdout.write(" read " + str(k))    
  for k in num_times:
    sys.stdout.write(" write " + str(k))
  sys.stdout.write("\n")

for k in num_times:  
  sys.stdout.write(" " + str(times_read[k]))
 
for k in num_times:  
  sys.stdout.write(" " + str(times_write[k]))
sys.stdout.write("\n")

